package com.wk.springbootlearn.controller;

import com.wk.springbootlearn.common.model.Response;
import com.wk.springbootlearn.service.HDFSService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Api(value = "hdfs测试", tags = "hdfs测试")
@RestController
@RequestMapping("/hdfs")
public class HDFSController {

    @Autowired
    private HDFSService hdfsService;

    @ApiOperation("遍历指定路径下的文件")
    @GetMapping("/list")
    public Response list(@RequestParam("path") String path) {
        return new Response().setData(hdfsService.List(path));
    }

    @ApiOperation("创建文件夹")
    @PostMapping("/mkdirs")
    public Response mkdirs(@RequestParam("dirs") String dirs) {
        return new Response().setData(hdfsService.mkdir(dirs));
    }

    @ApiOperation("创建文件")
    @PostMapping("/upload")
    public Response upload(@RequestParam("dirs") String dirs, @RequestParam("file")MultipartFile file) {
        try{
            Boolean res = hdfsService.upload(dirs,file.getOriginalFilename(), file.getInputStream());
            return new Response().setData(res);
        }catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @ApiOperation("删除文件")
    @DeleteMapping("/delete")
    public Response delete(@RequestParam("fileName") String fileName) {
        return new Response().setData(hdfsService.delete(fileName));
    }

    @ApiOperation("重命名文件")
    @PutMapping("/rename")
    public Response rename(@RequestParam("oldStr") String oldStr, @RequestParam("newStr") String newStr) {
        return new Response().setData(hdfsService.rename(oldStr, newStr));
    }

    @ApiOperation("文件是否存在")
    @GetMapping("/exist")
    public Response exist(@RequestParam("fileName") String fileName) {
        return new Response().setData(hdfsService.exists(fileName));
    }

    @ApiOperation("下载文件")
    @GetMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam("fileName") String fileName) throws IOException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8"));
        InputStream inputStream = hdfsService.download(fileName);
        return new ResponseEntity<byte[]>(IOUtils.toByteArray(inputStream),httpHeaders, HttpStatus.OK);
    }
}
